const app = getApp();
var util =  require('../../../utils/util.js');
var isBuy = false;
Page({

    /**
     * 页面的初始数据
     */
    data: {
      yunfei:0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        util.setNavBarTitle('确认订单');
        console.log(options);
        let _this = this;
        if(options.type == 1){
          _this.setData({
              productId:options.id
          })
        }
        this.setData({
            type:options.type
        })
        let type = options.type;
        //options.type 1 单个商品立即购买（直接使用id获取商品详情）    2购物车商品结算（直接获取购物车商品列表）
        this.getKitchen(type)
    },
    getKitchen(type){
        let _this = this;
        util.getAjax(`${app.globalData.apiUrl}/get_community_service_kitchen`,res=>{
            console.log(res);
            _this.setData({
                kitchenId:res.data.id,
                kitchenName:res.data.name
            })
            // _this.getKitchenClass(_this.data.type),
            // _this.getShoppingcartList();
            _this.getOrderList(type)
        },{
            community_id:app.globalData.communityId
        })
    },
    getOrderList(type){
      let _this = this;
      if(type == 1){
        util.getAjax(`${app.globalData.apiUrl}/get_community_service_kitchen_product_content`,res=>{
            console.log(res);
            let list = [];
            // list.push(res.data)
            // console.log(list);
            _this.setData({
                productInfo:res.data,
                totalMoney:(parseFloat(res.data.price)+parseFloat(_this.data.yunfei)).toFixed(2)
            })
        },{id:_this.data.productId})
      }else if(type == 2){
          util.getAjax(`${app.globalData.apiUrl}/get_community_service_kitchen_buycar`,res=>{
              console.log('shoppingcart',res);
              //计算总数
              let money = 0;
              for(var i in res.data){
                  money += res.data[i].num * res.data[i].price
              }
              _this.setData({
                  shoppingcartList:res.data,
                  shoppingcartNum:res.data.length,
                  totalMoney:(parseFloat(money)+parseFloat(_this.data.yunfei)).toFixed(2)
              })
          },{
              user_id:app.globalData.userId,
              kitchen_id:_this.data.kitchenId
          })
      }
    },
    //获取地址数据
    getAddressData:function(){
        var that = this
        util.getAjax(app.globalData.apiUrl +'/get_user_address',function(res){
            // console.log(res)
            if(res.data.length!=0){
                that.setData({
                    isAddress: true,
                    addressList: res.data[0],
                })
            }else{
                that.setData({
                    isAddress: false,
                    addressList: [],
                })
                util.showModelAll('提示','请添加收货地址',function(){
                    wx.navigateTo({
                        url: '/subPages/mine/newAddress/newAddress?isOne=' + 1,
                    })
                })
            }
        },{type:1,user_id: that.data.userId})
    },

    buy(){
        var _this = this;
        if(isBuy) return;
        isBuy = true;
        if(_this.data.isAddress){
            var addressList = _this.data.addressList;
            if(addressList){
                var order_content = {
                    user_id:addressList.user_id,
                    kitchen_id:_this.data.kitchenId,
                    sheng:addressList.sheng,
                    shi:addressList.shi,
                    qu:addressList.qu,
                    address:addressList.address,
                    name:addressList.name,
                    phone:addressList.phone,
                    order_price:_this.data.totalMoney
                };

                var all_product = [];
                var all_id = [];
                var type = _this.data.type;
                //单品购买立即
                if(type == 1){
                    var productInfo = _this.data.productInfo;
                    // console.log(productInfo);
                    var product = {
                        product_id: productInfo.id,
                        num:1,
                        one_price: productInfo.price,
                        all_price: productInfo.price
                    }
                    all_product.push(product);
                }
                //购物车结算
                if(type == 2){
                    var shoppingcartList = _this.data.shoppingcartList;
                    for(var i in shoppingcartList){
                        all_id.push(shoppingcartList[i].id);
                        var product = {
                            product_id:shoppingcartList[i].product_id,
                            num:shoppingcartList[i].num,
                            one_price:shoppingcartList[i].price,
                            all_price:shoppingcartList[i].num * shoppingcartList[i].price
                        }
                        all_product.push(product);
                    }
                }

                order_content = JSON.stringify(order_content);
                all_product = JSON.stringify(all_product);
                console.log(all_product, order_content,all_id);
                util.postAjax(`${app.globalData.apiUrl}/community_service_kitchen_pay`,res =>{
                    console.log(res);
                    var orderNum = res.data.out_trade_no;
                    wx.requestPayment({
                        timeStamp:res.data.timeStamp,
                        nonceStr:res.data.nonceStr,
                        package:res.data.package,
                        signType:res.data.signType,
                        paySign:res.data.paySign,
                        success(res){
                            if(res.errMsg == 'requestPayment:ok'){
                                util.getAjax(`${app.globalData.apiUrl}/community_service_kitchen_pay_ok`,res=>{
                                    console.log(res);
                                    if(res.data == 1){
                                        console.log('支付成功')
                                        wx.navigateTo({
                                            url:'/subPages/mine/orderDetails/orderDetails?orderNum='+orderNum+'&orderclass='+2
                                        })
                                        isBuy = false
                                    }
                                },{
                                    order_num:orderNum
                                })
                            }
                        },
                        fail(err){
                            console.log(err);
                            isBuy = false;
                            wx.navigateTo({
                                url:'/subPages/mine/orderDetails/orderDetails?orderNum='+orderNum+'&orderclass='+2
                            })
                        }
                    })

                },{
                    order_content:order_content,
                    all_product: all_product,
                    all_id:all_id,
                    user_id:app.globalData.userId
                })

            }else{
                util.showToast('加载失败，请重试','none',1000)
                isBuy = false
            }
        }else{
            isBuy = false
            util.showModelAll('提示','请添加收货地址',function(){
                wx.navigateTo({
                    url: '/subPages/mine/newAddress/newAddress?isOne=' + 1,
                })
            })
        }


    },

    //地址管理
    addressBtn:function(){
        wx.navigateTo({
            url: '/subPages/mine/address/address',
        })
    },

    //新增地址管理
    newAddressBtn:function(){
        wx.navigateTo({
            url: '/subPages/mine/newAddress/newAddress?isOne=' + 1,
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this
        if(app.globalData.userId){
            that.setData({
                userId: app.globalData.userId
            })
            that.getAddressData()
        }else{
            app.userIdCallback = userId => {
                if (userId != '') {
                    that.setData({
                        userId: userId
                    });
                    that.getAddressData()
                }
            }
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
